Code Contracts for .NET

Mark Leighton Fisher on 2009-03-20T20:36:11

Code Contracts for .NET "provide a language-agnostic way to express coding assumptions in .NET programs" (from their website). This lets .NET programmers -- whether C#, VB.NET, Iron Python, or whatever -- verify coding assumptions both statically and dynamically. (This is similar to Design by Contract in Eiffel.)

Code Contracts includes a static checker program for verifying both explicit and implicit (null references, array bounds, etc.) code contracts. Runtime (dynamic) contract checking can use marked series of If-Then-Throw guard clauses as in:

 
if ( x == null )
    throw new ArgumentNullException("x");
if ( y < 0 )
    throw new ArgumentOutOfRangeException(...);
Contract.EndContractBlock();
 

(so you don't waste perfectly good guard clauses) as well as the standard, explicit code contracts like:

 
    Contract.Invariant(this .y >= 0);
    Contract.Assert(this .x == 3,
     "Why isn't the value of x 3?");
    Contract.Requires(x ! = null,
     "DANGER -- missles fired!");
 

Code Contracts defaults at runtime to throwing an exception (System.Diagnostics.Contracts.ContractException) when a contract is violated (this behavior is configurable).

I have not tried Code Contracts (or any code contract mechanism) yet, but the idea is intriguing because it lets the computer do something it does well (exhaustive examination of your code in tedious detail) thereby freeing you to work on the higher-level aspects of your program, just as C freed us from assembly language bookkeeping and Perl/Java/VB.NET etc. free us from C language bookkeeping.

If anyone has experience with code contracts for any language (positive or negative), please comment.

(Ob. Perl ref. -- see Moose and Class::Contract among others...


But what's the overhead?

Ron Savage on 2009-03-21T04:21:19

Hi Mark

I can understand the theoretical arguments for all these asserts, but I can't actually envision writing such code in the real world.

And I don't think it's good enough to say people ought to - the simple fact is that, in general, they won't.

So, what are your thought on this :-)?

Re:But what's the overhead?

Mark Leighton Fisher on 2009-04-02T16:57:44

The ability to perform static analysis is what intrigued me about Code Contracts for .NET. Even in VB.NET (more strictly data-typed than Perl), I end up writing assertation-like code anyway for argument and return-value validation. It would be nice to leverage that validation code for some additional static analysis, without requiring strong data-typing everywhere all of the time.

If I was writing server code, I would probably also use some kind of runtime assertation mechanism, just because I like to have my servers run until someone trips over the power cord :).